package com.supermap.wzhy.common.service;

import org.hibernate.FlushMode;
import org.hibernate.Session;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.Iterator;
import java.util.List;

/**
 * Entity管理工厂服务
 *
 * <p style="color:red;">
 * &nbsp;&nbsp;注意： &nbsp;&nbsp;此类暂未使用
 * </p>
 *
 * @author Created by Administrator on 14-3-7.
 */
public abstract class EntityManagerFactoryService<K, T, S> extends
        ExcelOperateServices<T, S> {
    /** 实体管理工厂 */
    //private EntityManagerFactory entityManagerFactory;

    /**
     * 取得实体工厂管理对象
     *
     * @return
     */
    private EntityManagerFactory getEntityManagerFactory() {
        return Persistence
                .createEntityManagerFactory("permissionPersistenceUnit");
    }

    /**
     * 将实体List插入到数据库中
     *
     * @param entityList
     *            实体列表
     * @return 插入结果，true代表成功
     */
    public boolean insertEntities(List<K> entityList, int batchSize) {
        try {
            EntityManager entityManager = getEntityManagerFactory()
                    .createEntityManager();
            EntityTransaction entityTransaction = entityManager
                    .getTransaction();
            entityTransaction.begin();
            Session session = (Session) entityManager.getDelegate();
            session.setFlushMode(FlushMode.MANUAL);
            Iterator iterator = entityList.iterator();
            int i = 0;
            while (iterator.hasNext()) {
                i++;
                session.save(iterator.next());
                if (i % batchSize == 0) {
                    session.flush();
                    session.clear();
                }
            }
            entityTransaction.commit();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

}
